#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4
"""
    @author jay.han
"""

from celery import current_task
from celery import task

import logging
from cvirt.common import utils
from cvirt.tasks import link_sync_call, TaskWrap
from cvirt.common.constant import TaskAction
from cvirt.manager.models import TaskDetail

api = utils.cnode_import_class('cvirt.cnode.storage.api')

LOG = logging.getLogger(__name__)

#初始化已经存在或者已经删除的存储
if api: api.init_storages()

@TaskWrap
@link_sync_call
@task()
def attach(storage,uuid=None):

    LOG.info("attach storage %s" % storage.name)
    current_task.update_state(state="building")
    first = TaskDetail.create_if_not_exsist(uuid,name=TaskAction.ADD_STORAGE,type=TaskAction.STORAGE,
                                  target=storage.name,meta_id=current_task.request.id)
    try:
        api.attach(storage)
        if first:
            try:
                if storage.type != 'iso':
                    info = api.get_storage_info(storage)
                    storage.update(dict(totalsize=info['size'],used=info['used']))
            except Exception as e:
                LOG.warn('get storage %s usage failed:%s' % (storage.name, e))

        storage.update(dict(status='running'))
        LOG.info('attach storage %s successful' % storage.name)
    except Exception as e:
        storage.delete()  #链式调用中有一个失败则删除数据
        LOG.info('attach storage %s failed' % storage.name)
        LOG.exception("exception:%s" % e)
        raise


@TaskWrap
@link_sync_call
@task()
def detach(storage,uuid=None):

    current_task.update_state(state="building")
    TaskDetail.create_if_not_exsist(uuid,name=TaskAction.REMOVE_STORAGE,type=TaskAction.STORAGE,
                          target=storage.name,meta_id=current_task.request.id)
    try:
        api.detach(storage)
        storage.remove()
        LOG.info('detach storage %s successful' % storage.name)
    except:
        LOG.info('detach storage %s failed' % storage.name)
        raise


@TaskWrap
@task()
def list_isos(storages,uuid=None):
    try:
        return api.isos(storages)
    except:
        LOG.info('list isos failed')
        raise


# @task()
# def discover_targets(storage):
#     try:
#         api.discover_target(storage)
#     except:
#         raise
#
#
# @task()
# def discover_luns(target):
#     try:
#         api.discover_luns(target)
#     except:
#         raise
